<template>
  <div v-loading="loading" class="markBox">
    <div>
      <el-button type="primary" @click="click1">锚点区域</el-button>
      <el-button type="primary" @click="click2">帮助指引</el-button>
      <el-button type="primary" @click="click3">遮盖区域</el-button>
    </div>
    <div class="imgbox" id="imgbox" ref="at">
      <ui-marker
          ref="aiPanel-editor"
          class="ai-observer"
          v-bind:uniqueKey="uuid"
          :ratio="1"
          @vmarker:onAnnoSelected="onAnnoSelected"
          @vmarker:onUpdated="onUpdated"
          @vmarker:onReady="onReady"
          @vmarker:onImageLoad="onImageLoad"
          @vmarker:onDrawOne="onDrawOne"
          v-bind:readOnly="readOnly"
          v-bind:imgUrl="currentImage"
      >
      </ui-marker>
    </div>



    <div v-for="(itemParent,indexParent) in blist" :key="indexParent"
         :style="{position:'absolute',left: itemParent.tranLeft, top: itemParent.tranTop}" class="addMark">
      <div v-if="itemParent.type == 1">
        <el-input v-model="itemParent.input" placeholder="请输入按钮名称"></el-input>
        <el-select  v-model="itemParent.text" allow-create filterable default-first-option
                    @change="markChange" size="small" style="width:100%" placeholder="请选择需要链接的页面">
          <el-option
              v-for="(item,index) in list"
              :key="index"
              :label="item.content"
              :value="item.content">
          </el-option>
        </el-select>
      </div>
      <div v-if="itemParent.type == 2">
        <el-input v-model="itemParent.input" type="textarea" placeholder="请输入帮助指引内容"></el-input>

      </div>
    </div>


  </div>
</template>
<script>
import { AIMarker } from "vue-picture-bd-marker";
export default {
  components: {"ui-marker": AIMarker},
  data() {
    return {
      uuid: "0da9130",
      readOnly: true, //是否只读
      // width: '80%', //宽度
      currentImage: require('@/assets/images/img.png'),
      blist: [],
      text: '2',
      markSelect: false,//锚点区域
      helpGuide: false,//帮助指引
      cover: false,//遮盖
      total: 0,
      tranLeft: '',
      tranTop: '',
      loading:false,
      list:[
        {content:'1'},
        {content:'2'},
        {content:'3'},
      ]
    }
  },
  watch:{
    text(){
      if (this.uuid != '') {
        let blist = this.blist
        blist.forEach(i => {
          if (this.uuid == i.uuid) {
            this.$refs['aiPanel-editor'].getMarker().setTag({
              tagName: this.text,
              tag: "0x0001"
            });
            i.tagName = this.text
          }
        });
        this.blist = blist
        this.dialogVisible = false
        this.uuid = ''
        this.text = ''
      }
    },
  },
  methods: {
    onReady(){

      // uniqueKey 识别控件唯一性，当页面存在多个控件时需要区分 默认值：无
      // readOnly 是否只作显示 默认值：false
      // width 宽(单位：像素、百分比) 默认值：100%
      // ratio 控件宽高比例 默认值：16/9  ratio:0 使用原图像缩放比
      // imgUrl 图片url 默认值：无
      // vmarker:onImageLoad 图片加载完成后回调，不包含data:image格式。回调参数,data={rawW,rawH,currentW,currentH}
      // vmarker:onReady 当控件准备完成后回调，参数为uniqueKey
      // vmarker:onDrawOne 当画完一个标注框时回调，参数为data【标注数据】, uniqueKey
      // vmarker:onSelect 当选中图片上的标注框时回调，参数为data【标注数据】, uniqueKey
      // vmarker:onUpdated 当标注框位置或者标框属性发生改动时回调，参数为data【标注数据】, uniqueKey
      // vmarker:onDataRendered 当标注框主动渲染数据后时回调，参数为uniqueKey
    },
    //图片加载完成后回调
    onImageLoad(){
      this.$refs['aiPanel-editor'].getMarker().renderData([
        {
          tag: "id04",
          tagName: "蜜蜂",
          position: {
            x: "41.026%",
            x1: "53.790000000000006%",
            y: "22.678%",
            y1: "40.496%"
          },
          uuid: "5559A20B25712D9D"
        }
      ]);
      this.markSelect = true
    },
    click1(){
      this.markSelect = true;
      this.helpGuide = false;
      this.coverCon = false;
      this.readOnly = false;
    },
    click2(){
      this.helpGuide = true;
      this.markSelect = false;
      this.coverCon = false;
      this.readOnly = false;
    },
    click3(){
      this.helpGuide = false;
      this.markSelect = false;
      this.coverCon = true;
      this.readOnly = false;
    },
    // 圈选一个矩形回调
    onDrawOne(e,uniqueKey){
      this.uuid = uniqueKey //选中区域后展示select，在对应的区域下方
      // this.readOnly = true;
      if (this.total > 5) {
        this.markSelect = false
      }
    },
    markChange(){},
    //提交
    toImage(){
      // 没有标注提示
      if (this.blist.length == 0){
        this.$message({
          message: '请选择标注',
          type: "error",
        });
        return
      }
      this.loading = true
      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等

      //   api_UploadImg(formData)
      //       .then((res) => {
      //         this.loading = false
      //       })
      //       .catch((error) => {
      //       });
      // });
    },
    onAnnoSelected(e){
      this.uuid = e.uuid;
      console.log('onAnnoSelected')
    },
    onUpdated(e,KEY){
      console.log("选框位置或者标框属性发生改动", KEY);

      e.forEach(item=>{
        item.tranLeft = Number(item.position.x.replace('%', '')) / 100 * document.querySelector('.imgbox').offsetWidth + 'px'
        item.tranTop = Number(item.position.y1.replace('%', '')) / 100 * document.querySelector('.imgbox').offsetHeight + 20 + 'px' //限制标注个数超过5个时隐藏select
      })

      if(this.markSelect){
        e[e.length-1].type = 1
      }
      if(this.helpGuide){
        e[e.length-1].type = 2
      }
      if(this.cover){
        e[e.length-1].type = 3
      }

      console.log('list',e)
      this.blist = e;
      this.uuid = ''
      this.text = ''
      // 限制标注个数
      this.total = 0
      const markBox = document.getElementById('imgbox')
      const markers = markBox.querySelectorAll('.annotation')
      if(this.coverCon){
        markers[e.length-1].style.backgroundColor = 'green'
      }
      for (let i = 0; i < markers.length; i++) {
        if (markers[i].clientWidth !== 0) {
          this.total++
        }
        if (this.total > 10) {
          this.$message.warning('最多只可标记五处！')
          markers[i].remove()
        }
      }//如果有重复的标注时新添加的标注覆盖已有的
      // let arr1 = []
      // let peon = e.reduce((cur, next) => {
      //   let index = cur.findIndex(item => item.tagName == next.tagName)
      //   if (index != -1) {
      //     arr1.push(cur[index])
      //     cur.splice(index, 1)
      //   }
      //   cur.push(next)
      //   return cur;
      // }, [])
      // this.blist = peon
      // e = peon
      // 重复项新的替换旧的
      for (var i = 0; i < markers.length; i++) {
        let arr = e.findIndex(item => item.uuid == markers[i].getAttribute('data-uuid'))
        // console.log(arr)
        if (arr == -1) {
          markers[i].remove()
        }
      }
    },
  }
}
</script>
<style lang="scss">
.markBox{
  position: relative;
  .imgbox{
    width: 60%;
    height: 500px;
  }
  .addMark{
    position: absolute;
    z-index: 99999;
  }
}

</style>
